﻿

$$.LazyImager = function (Node, Horiz) {
	var me = this;
	if (!Node) Node = document.body || document.documentElement;
	var Imgs = [], execing = false;
	function finish() {
		execing = false;
		Imgs = [];
	}
	var shows = function (evt) {
		var w = Horiz ? Node.clientWidth : Node.clientHeight;
		var t = Horiz ? Node.scrollLeft : Node.scrollTop;
		var top = t - w + 3;
		var bot = w * 2 + t - 3;
		var num = 0, len = Imgs.length - 1;
		for (var i in Imgs) {
			var img = Imgs[i];
			if (!img || !img.LazyShow) { delete Imgs[i]; continue; }
			if (img.Lazy0 > bot || img.Lazy9 < top) { num++; continue; }
			delete Imgs[i];
			img.LazyShow();
		}
		if (num < 1) finish();
	}

	me.Move = function () {
		if (!execing) return;
	    shows();
	};
	me.Start = function () {
		Imgs = [];
		var p = Node.getBoundingClientRect();
		var otop = Horiz ? Node.scrollLeft - p.left : Node.scrollTop - p.top;
		function off(img) {
		    //img.off("click", img.LazyShow);
			img.removeAttribute("lazy-src");
		    delete img.Lazyer;
		}
		function each(i, img) {
		    if (img.Lazyer && img.Lazyer !== me) return;
			var src = (img.getAttribute("lazy-src")||"").trim();
			if (!src) { off(img); return; }
			img.Lazyer = me;
			//img.style.cssText = "opacity:0.5;transition:opacity 800ms ease;-webkit-transition:opacity 800ms ease";
			var pos = img.getBoundingClientRect();
			if (pos.top === pos.bottom || pos.left === pos.right || pos.width<=0 || pos.height <= 0) return;
			img.Lazy0 = (Horiz ? pos.left : pos.top) + otop;
			img.Lazy9 = (Horiz ? pos.right : pos.bottom) + otop;
			Imgs.push(img);
			if (!img.LazyShow) img.LazyShow = function () {
				off(img);
				var im = new Image();
				im.onload = function () {
					if ((img.tagName||img.nodeName||"").toLowerCase() === "img") img.setAttribute("src", im.src);
					else img.style.backgroundImage = "url(" + im.src + ")";
					//img.style.opacity = "1";
				};
				im.src = src;
			};
		}
		$("[lazy-src]", Node).each(each);
		if (Imgs.length < 1) return;
		execing = true;
		me.Move();
	};
};
$$.LazyImager.Shows = function (Node) {
    if (!Node) return;
    $("[lazy-img]", Node).each(function (i, img) {
        var src = (img.getAttribute("lazy-img") || "").trim();
        img.removeAttribute("lazy-img");
        var im = new Image();
        im.onload = function () {
            if ((img.tagName || img.nodeName || "").toLowerCase() === "img") img.setAttribute("src", im.src);
            else img.style.backgroundImage = "url(" + im.src + ")";
        };
        im.src = src;
    });
    $("[lazy-sorc]", Node).each(function (i, node) {
    	var src = (node.getAttribute("lazy-sorc") || "").trim();
    	node.removeAttribute("lazy-sorc");
    	node.src = src;
    });
};